package com.ruoyi.statistics.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.company.service.ICompanyOtherServer;
import com.ruoyi.sale.domain.SaleGoodsOrder;
import com.ruoyi.statistics.domain.ProductStatistics;
import com.ruoyi.statistics.domain.Statistics;
import com.ruoyi.statistics.service.StatisticsService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 销售统计对象 statistics
 *
 * @author zjh
 * @date 2022-06-17
 */
@RestController
@RequestMapping("/statistics")
public class StatisticsController extends BaseController {

    private String prefix = "statistics";
    @Autowired
    private StatisticsService statisticsService;
    @Autowired
    private ICompanyOtherServer iCompanyOtherServer;

    public static void main(String[] args) {
        // 1. 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // 2. 解析传入的日期参数
        String inputDate = "2024-02-24";
        LocalDate date = LocalDate.parse(inputDate, formatter);

        // 3. 精确减1年（自动处理闰年）
        LocalDate previousYearDate = date.minusYears(1);

        // 4. 格式化输出
        String outputDate = previousYearDate.format(formatter);
        System.out.println(outputDate); // 2023-02-24
    }

    @RequiresPermissions("business:clientStatistics:view")
    @GetMapping("/clientStatistics")
    public Map<String, Object> clientStatistics() {
        Map<String, Object> resMap = new HashMap<>();
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        Long companyId = sysUser.getCompanyId();
        Map<String, Object> map = new HashMap();

        resMap.put("deptId", companyId);
        if (!sysUser.getDeptId().equals(sysUser.getCompanyId())) {

            resMap.put("userId", sysUser.getUserId());
        }
        List<SaleGoodsOrder> saleGoodsOrders = iCompanyOtherServer.selectDeptObjMap(map);
        for (int i = saleGoodsOrders.size() - 1; i >= 0; i--) {
            if (saleGoodsOrders.get(i) == null) {
                saleGoodsOrders.remove(i);
            }
        }
        resMap.put("deptObj", saleGoodsOrders);
//        model.addAttribute("deptObj",iCompanyOtherServer.selectDeptObj(ShiroUtils.getSysUser().getCompanyId()));
        return resMap;
    }

    @RequiresPermissions("business:productStatistics:view")
    @GetMapping("/productStatistics")
    public Map<String, Object> productStatistics() {

        Map<String, Object> resMap = new HashMap<>();
        resMap.put("deptObj", statisticsService.selectDeptObj(SecurityUtils.getLoginUser().getUser().getCompanyId()));
        resMap.put("typeObj", statisticsService.selectProductStatisticsTypeList(SecurityUtils.getLoginUser().getUser().getCompanyId()));
        return resMap;
    }

    /**
     * 查询客户销售统计
     */
    @RequiresPermissions("business:clientStatistics:list")
    @GetMapping("/clientStatisticsList")
    @ResponseBody
    public TableDataInfo clientStatisticsList(@RequestParam(value = "deptName", required = false) String deptName,
                                              @RequestParam(value = "beginTime", required = false) String beginTime,
                                              @RequestParam(value = "endTime", required = false) String endTime) {
        Statistics statistics = new Statistics();
        statistics.setBeginTime(beginTime);
        statistics.setEndTime(endTime);
        statistics.setDeptName(deptName);
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        startPage();
        if (!sysUser.getDeptId().equals(sysUser.getCompanyId())) {
            statistics.setUserId(sysUser.getUserId());
        }
        List<Statistics> list = statisticsService.selectClientStatisticsList(statistics);
        return getDataTable(list);
    }

    /**
     * 查询客户销售统计 总计
     */
    @GetMapping("/clientStatisticsListCount")
    @ResponseBody
    public AjaxResult clientStatisticsListCount(@RequestParam(value = "deptName", required = false) String deptName,
                                                @RequestParam(value = "beginTime", required = false) String beginTime,
                                                @RequestParam(value = "endTime", required = false) String endTime) {
        Statistics statistics = new Statistics();
        statistics.setBeginTime(beginTime);
        statistics.setEndTime(endTime);
        statistics.setDeptName(deptName);
        Statistics statistics1 = statisticsService.selectClientStatisticsListCount(statistics);
        return AjaxResult.success(statistics1);
    }

    /**
     * 查询产品销售统计
     */
    @RequiresPermissions("business:productStatistics:list")
    @GetMapping("/productStatisticsList")
    @ResponseBody
    public TableDataInfo productStatisticsList(@RequestParam(value = "productName", required = false) String productName,
                                               @RequestParam(value = "productType", required = false) String productType,
                                               @RequestParam(value = "beginTime", required = false) String beginTime,
                                               @RequestParam(value = "endTime", required = false) String endTime) {

        ProductStatistics productStatistics = new ProductStatistics();
        SysUser sysUser = SecurityUtils.getLoginUser().getUser();
        productStatistics.setBeginTime(beginTime);
        productStatistics.setEndTime(endTime);
        productStatistics.setProductName(productName);
        productStatistics.setProductType(productType);
        startPage();
        if (!sysUser.getDeptId().equals(sysUser.getCompanyId())) {
            productStatistics.setUserId(sysUser.getUserId());
        }
        List<ProductStatistics> list = statisticsService.selectProductStatisticsList(productStatistics);
        return getDataTable(list);
    }

    /**
     * 查询产品销售统计 总计
     */
    @PostMapping("/productStatisticsListCount")
    @ResponseBody
    public AjaxResult productStatisticsListCount(ProductStatistics productStatistics) {
        if (!ShiroUtils.getSysUser().getDeptId().equals(ShiroUtils.getSysUser().getCompanyId())) {
            productStatistics.setUserId(ShiroUtils.getUserId());
        }
        ProductStatistics productStatistics1 = statisticsService.selectProductStatisticsListCount(productStatistics);
        if (productStatistics1 == null) {
            productStatistics1 = new ProductStatistics();
        }
        return AjaxResult.success(productStatistics1);
    }

    /**
     * 查询每月预警值列表
     */
    @RequiresPermissions("business:productStatistics:list")
    @PostMapping("/selectTypeByName")
    @ResponseBody
    public TableDataInfo selectTypeByName(String productName) {
        startPage();
        ProductStatistics productStatistics = new ProductStatistics();
        productStatistics.setProductName(productName);
        List<ProductStatistics> list = statisticsService.selectProductStatisticsTypeByNameList(productStatistics);
        return getDataTable(list);
    }

    /**
     * 查询每月预警值列表
     */
    @RequiresPermissions("business:productStatistics:list")
    @PostMapping("/selectProductStatisticsTypeList")
    @ResponseBody
    public TableDataInfo selectProductStatisticsTypeList() {
        startPage();
        List<ProductStatistics> list = statisticsService.selectProductStatisticsTypeList(ShiroUtils.getSysUser().getCompanyId());
        return getDataTable(list);
    }


    /**
     * 导出定时任务列表
     */
    @RequiresPermissions("business:task:export")
    @Log(title = "定时任务", businessType = BusinessType.EXPORT)
    @PostMapping("/exportProduct")
    @ResponseBody
    public AjaxResult exportProduct(ProductStatistics productStatistics) {
        Long companyId = ShiroUtils.getSysUser().getCompanyId();
        productStatistics.setCompanyId(companyId);
        List<ProductStatistics> list = statisticsService.selectProductStatisticsList(productStatistics);
        ExcelUtil<ProductStatistics> util = new ExcelUtil<ProductStatistics>(ProductStatistics.class);
        return util.exportExcel(list, "产品销售数据");
    }

    /**
     * 导出定时任务列表
     */
    @RequiresPermissions("business:task:export")
    @Log(title = "定时任务", businessType = BusinessType.EXPORT)
    @PostMapping("/exportClient")
    @ResponseBody
    public AjaxResult exportClient(Statistics statistics) {
        Long companyId = ShiroUtils.getSysUser().getCompanyId();
        statistics.setCompanyId(companyId);
        List<Statistics> list = statisticsService.selectClientStatisticsList(statistics);
        ExcelUtil<Statistics> util = new ExcelUtil<Statistics>(Statistics.class);
        return util.exportExcel(list, "客户销售数据");
    }
}
